<%@page import="org.apache.http.client.HttpClient, org.apache.http.impl.client.*,
        org.apache.http.client.methods.*,org.apache.commons.io.*,
        java.io.* "   contentType="text/html;charset=UTF-8" %>

<%

    String url = request.getParameter("url");
    // url = java.net.URLEncoder.encode(url, "UTF-8");
    //out.println(url + "<br/>");
    String f[] = url.split("\\$");
    String q = request.getParameter("q");
    String urlNotNeedCon = null;
    String outputFormat = null;
    if (f.length == 1) {
      //url = f[0];
      urlNotNeedCon = f[0].replaceAll(" ", "%20"); // java.net.URLEncoder.encode(f[0], "UTF-8");
    } else if (f.length == 2) {
      urlNotNeedCon = f[0].replaceAll(" ", "%20"); //java.net.URLEncoder.encode(f[0], "UTF-8");
      outputFormat = f[1];
      if (outputFormat.endsWith("swf")) {
        outputFormat = "swf";
      }
    }
    if ("swf".equals(outputFormat)) {
%>
<script type="text/javascript" src="swfobject/swfobject.js"></script>
<%            } else {
%>


<script type="text/JavaScript" src ="js/jquery-1.4.3.min.js" > </script>




<script type="text/JavaScript" >
  //for ativex purpose.
  error = 0;

  function getXMLHttpRequest()
  {
    if (window.XMLHttpRequest) {
      return new window.XMLHttpRequest;
    }
    else {
      try {
        return new ActiveXObject("MSXML2.XMLHTTP");
      }
      catch(ex) {
        return null;
      }
    }
  }
  // this fn is invoked if IE
  function IeBinFileReaderImpl(fileURL, q){
     
    if ($.browser.mozilla) {
      // alert("mozilla");
      try {
        document.getElementById('activeXId').loadContentDirect(fileURL, q); 
      } catch(e)
      {
        alert(e);
      }
 
      return 1; // good.
    }
    this.req = getXMLHttpRequest();
    //this.req.setRequestHeader("Accept-Charset", "x-user-defined");
    if ($.browser.mozilla){
      req.overrideMimeType('text/plain; charset=x-user-defined');
    }
    try {
      this.req.open("GET", fileURL, true);
    } catch(e)
    {
      //alert(e + fileURL);
     
      h = document.getElementById('activeXId').loadContentDirect(fileURL, q);
      if (h == 0 )
      {
        //alert("any");
        newURL = "http://elookinto.com/elconverter/txconv/?redirect=true&url=" + fileURL;
        // alert(newurl);
        // IeBinFileReaderImpl(newurl, q);
        return newURL;
      }
      return h;
    }
   
    that = this;
    this.req.onreadystatechange = function(event){
        
      if (that.req.readyState == 4) {
        that.status = "Status: " + that.req.status;
        //that.httpStatus = that.req.status;
        if (that.req.status == 200) {
          
          if ($.browser.msie)
            document.getElementById('activeXId').loadContent( that.req.responseBody, that.req.responseText, fileURL, q);
          else {
          
            document.getElementById('activeXId').loadContent( that.req.responseText, that.req.responseText, fileURL, q);
          }
        } else {
          
        }
        if (typeof callback == "function"){ callback(that);}
      }
    };
    this.req.send();
    return 0;
  }
  //$.getScript("http://<=host/elconverter/licenselogs.jsp?page=viewer");
  // showApplet();

  $(document).ready( function() {
   
    var ax = document.getElementById('activeXId');
    q = '<%= q%>';
    if (ax != null) {
      ret =  IeBinFileReaderImpl("<%=urlNotNeedCon%>", q);
      //  alert(ret);
      //document.write(ret);
      if (ret.length > 4)
      {
        IeBinFileReaderImpl(ret, q);
      }
    }
  });

</script>

<% }

    //out.println("---url " + url + "<br/>");
    //out.println("format= " + outputFormat + "<br/>");
    //if (true) return;
    String useragent = request.getHeader("User-Agent");


    String user = useragent.toLowerCase();
    boolean ie = false;
    if (user.indexOf("msie") >= 0) {
      ie = true;
    }


    if (url != null || url.trim().length() != 0) {
      if (!"swf".equals(outputFormat)) {
        if (ie) {%>

<%--
<button onclick=" IeBinFileReaderImpl('http://localhost:9080/elconverter/docs/snow.doc')"> testing </button>

F3164316-84A1-4AEE-A4CE-C451AC23C946
3e9e2c28-96c8-30ff-94d1-402f3f0548a3 --%>
<object id="activeXId" classid="CLSID:F3164316-84A1-4AEE-A4CE-C451AC23C946" style="margin:0px"
        height="95%" width="100%" onerror="error=1;">
  <param name="Query" value="<%= q%>"/>
  <h3> <B> <font size="-1" color="brown"> Please install <a href="download.jsp">Embeded ELookintoViewer/Editor </a> and Restart your browser for MUCH BETTER display</font> </B> <br/>
  </h3>

  <p>
  <h4>
    You may see some <a href="/elconverter"> Snap-shots  </a>. You are encouraged to buy a license for merely $5 at <a href="http://elookinto.com/elookinto">elookinto </a>
  </h4>
</p>
<%
          String src = null;
          if (url.contains("Oscar.rtf")) {
            src = "docs/oscar-rtf.PNG";
          }
          if (url.contains("Oscar.docx")) {
            src = "docs/oscar-docx.PNG";
          }
          if (url.contains("snow.doc")) {
            src = "docs/snow.PNG";
          }
          if (url.contains("sitelist.rtf")) {
            src = "docs/sitelist.PNG";
          }
          if (src != null) {%>
<div align="center">
  <h2> <font color="red"> If you had installed the viewer, it would have shown the doc as following</font> </h2>
  <img src="<%=src%>"/>
  <hr/>
</div>
<br/>
<% }%>
</object>
<% } else if (user.indexOf("zilla") >= 0) {%>

<object id="activeXId"
        TYPE="application/x-itst-activex"
        ALIGN="baseline" BORDER="0"
        WIDTH="100%" HEIGHT="100%"
        clsid="{F3164316-84A1-4AEE-A4CE-C451AC23C946}"
        event_OnReadyStateChange="OnReady"
        param_Query="<%=q%>"
        onerror="error=1;">
  <param name="Query" value="<%= q%>"/>
  <h3> <B> <font size="-1" color="brown"> Please install <a href="download.jsp">Embeded ELookintoViewer/Editor </a> and Restart your browser for MUCH BETTER display</font> </B> <br/>
  </h3>

  <p>
  <h4>
    You may see some <a href="/elconverter"> Snap-shots  </a>. You are encouraged to buy a license for merely $5 at <a href="http://elookinto.com/elookinto">elookinto </a>
  </h4>

  <%
            String src = null;
            if (url.contains("Oscar.rtf")) {
              src = "docs/oscar-rtf.PNG";
            }
            if (url.contains("Oscar.docx")) {
              src = "docs/oscar-docx.PNG";
            }
            if (url.contains("snow.doc")) {
              src = "docs/snow.PNG";
            }
            if (url.contains("sitelist.rtf")) {
              src = "docs/sitelist.PNG";
            }
            if (src != null) {%>
  <div align="center">
    <h2> <font color="red"> If you had installed the viewer, it would have shown the doc as following</font> </h2>
    <img src="<%=src%>"/>
    <hr/>
  </div>
  <br/>
  <% }%>
</object>



<%}%>

<script type="text/JavaScript" >
 
//alert("<%= url%>");
// d1 = new Date();
//document.getElementById('activeXId').TextVal = "<%= url%>";
  /* <% System.out.println(url.replace("converted", "txconv"));
            //int qmark = url.indexOf('?');
            //int dollar = url.indexOf('$');
            //String fileContentURL = url.substring(qmark + 5, dollar);
            //String fileExt = FilenameUtils.getExtension(fileContentURL);


  %> */

  /*else if (document.getElementById('appletId') != null) {
      $.ajax({ url: "<%= url%>",  success: function(data) {
          // alert(data);
          //alert(d1.getTime() - (new Date()).getTime())
          document.getElementById('appletId').setRtf(data);
        }
      });}*/

</script>
<%
      } else if (("swf").equals(outputFormat)) {
        //WebClient wc = new WebClient();
        url = "http://elookinto.com/elconverter/converted/?url=" + url; //http://localhost:9080/elconverter/docs/sitelist.pdf$.swf";
        url = url.replaceAll(" ", "%20");
        java.net.URL myURL = new java.net.URL(url);

        String swifturl = this.getServletContext().getContextPath() + IOUtils.toString(myURL.openStream()).trim();
        //out.println("swift url=" + swifturl);

%>

<div align=center>
  <script type="text/javascript">
 
  var flashvars = {
    doc_url: "<%=swifturl%>",
    zoomHome: "6"
  };
  var params = {
    menu: "false",
    bgcolor: '#efefef',
    allowFullScreen: 'true',
    zoomHome: '4'
  };
  var attributes = {
    id: 'website'
  };
  swfobject.embedSWF('zviewer.swf', 'website', '100%', '800', '9.0.45',
  'swfobject/expressinstall.swf', flashvars, params, attributes);
  </script>

  <div id="website">
    <p align="center" class="style1">In order to view this page you need Flash Player 9+ support!</p>
    <p align="center">
      <a href="http://www.adobe.com/go/getflashplayer">
        <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />                </a>            </p>
  </div>
</div>


<%

      } else if (("pdf").equals(outputFormat)) {

        response.sendRedirect(url + "#search=%22" + q + "%22");

      } else if ("html".endsWith(outputFormat)) {
        //System.out.println(j.encode(url, "utf-8"));
        url = url.replaceAll(" ", "%20");
        //java.net.URL tempURL = new java.net.URL(url);
        HttpClient hc = new DefaultHttpClient();
        HttpGet pm = new HttpGet(url);

        //http://localhost:9080/elconverter/converted?url=http://biosciences.stanford.edu/BMIPhDSupplement2010.doc|html
        BufferedReader br = new BufferedReader(new InputStreamReader(hc.execute(pm).getEntity().getContent(), "UTF8"));
        String line;
        while ((line = br.readLine()) != null) {
          out.println(line);
        }
        //IOUtils.copy(pm.getResponseBodyAsStream(), response.getOutputStream())
        out.println("<script type='text/JavaScript'> parent.highlightSearchTerms('" + q + "', false, true, null, null, document);</script> ");
      }
    }%>
<!--
      <button style="display:none" onclick="alert(document.getElementById('myId').getRtf())" > test </button> -->


